package com.xmg.mgrsite.filter;

import java.io.File;
import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;

import com.xmg.p2p.base.util.BidConst;

/**
 * 同步图片filter
 *
 */
public class SyncImgFilter implements Filter {

	private ServletContext ctx ; // Servlet的容器 可以用来获取真实路径

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,	FilterChain chain) throws IOException, ServletException {
		//web的请求都是HttpServletRequest类型的请求
		HttpServletRequest req = (HttpServletRequest) request ;
		HttpServletResponse resp = (HttpServletResponse) response ;
		File sourceFile  = new File(ctx.getRealPath(req.getRequestURI()));
		if (sourceFile.exists()) {
			chain.doFilter(request, response);
		}else{
			File publicFile = new File(BidConst.PUBLIC_IMG_PATH, FilenameUtils.getName(req.getRequestURI()));
			if (publicFile.exists()) {
				FileUtils.copyFile(publicFile, sourceFile) ;   //这里不可以直接放行
				resp.setHeader("Pragma", "no-cache");
				resp.setDateHeader("Expires", 0);
				ServletOutputStream responseOutputStream = response.getOutputStream();
				responseOutputStream.write(FileUtils.readFileToByteArray(publicFile));
				responseOutputStream.flush();
				responseOutputStream.close();
			}
		}
	
	/*HttpServletRequest req = (HttpServletRequest) request ;
		String fileName = req.getRequestURI();
		 fileName = ctx.getRealPath(fileName) ;
		 System.out.println(fileName);//http://localhost:8080/upload/xxxx.jpg
		chain.doFilter(request, response);
	//http://localhost:8080/upload/xxxx.jpg
//	D:\MAVENProjectApps\mgrsite\src\main\webapp/upload/xxxx.jpg
	*/
	}
	

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.ctx =filterConfig.getServletContext();
	}
	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

}
